
# -*- coding: utf-8 -*-

import ctypes
import inspect
import socket
import datetime


class KitUtil:
    @staticmethod
    def centerWin(frame, width, height):
        screenwidth = frame.winfo_screenwidth()
        screenheight = frame.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        frame.geometry(size)

    @staticmethod
    def async_raise(tid, exctype):
        """raises the exception, performs cleanup if needed"""
        try:
            tid = ctypes.c_long(tid)
            if not inspect.isclass(exctype):
                exctype = type(exctype)
            res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
            if res == 0:
                # pass
                raise ValueError("invalid thread id")
            elif res != 1:
                # """if it returns a number greater than one, you're in trouble,
                # and you should call it again with exc=NULL to revert the effect"""
                ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
                raise SystemError("PyThreadState_SetAsyncExc failed")
        except Exception as err:
            print(err)

    @staticmethod
    def stop_thread(thread):
        """终止线程"""
        if thread:
            KitUtil.async_raise(thread.ident, SystemExit)

    @staticmethod
    def get_host_ip():
        """
        查询本机ip地址
        :return:
        """
        s = None
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 80))
            ip = s.getsockname()[0]
        finally:
            if not s:
                s.close()
        return ip

    @staticmethod
    def getCrtTime():
        # return time.strftime('%Y-%m-%d %H:%M:%S.%f', time.localtime(time.time()))
        return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
